package com.ns002.yigou.quote.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author xu
 * @Date 2017/7/27 0027 下午 3:21
 */
@Service
public class DatabaseService {

    @Autowired
    EntityManager em;
    static Logger log = LoggerFactory.getLogger("database-share-table");

    /**
     * 创建表
     */
    @Transactional
    public void createTable(){

        long weekTime = 60000 * 60 * 24 * 7;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(new Date().getTime() + weekTime));  //创建下一周的表
        //第几周
        int week = calendar.get(Calendar.WEEK_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);

        String tableName = "mk_realtime_quote_" + year + "_" + week;

        String sql = "create table " + tableName + " (id integer not null auto_increment, contract varchar(255) not null, quote double precision not null, timestamp bigint not null, primary key (id))";

        try{
            em.createNativeQuery(sql).executeUpdate();   //创建出现异常表明表已存在
        } catch (PersistenceException e){
            log.error("表已创建");
            return;
        }


        createIndex(tableName, "contractIndex", "contract");
        createIndex(tableName, "timestampIndex", "timestamp");
        createIndex(tableName, "quoteIndex", "quote");
    }

    /**
     * 创建索引
     * @param tableName
     * @param indexName
     * @param indexCloumn
     */
    private void createIndex(String tableName, String indexName, String indexCloumn){
        String sql = "create index " + indexName +" on " + tableName + " (" + indexCloumn +")";
        em.createNativeQuery(sql).executeUpdate();
    }

}
